#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/13 13:52
# File  : serializers.py

"""

"""

from rest_framework import serializers
from sqlaudit.models import DatabaseConfig, AuditSQL
from utils.pass_crypt import PasswordCrypt


class DatabaseConfigSerializer(serializers.ModelSerializer):

    utime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    ctime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)

    def create(self, validated_data):
        pcrypt = PasswordCrypt()
        validated_data['password'] = pcrypt.encrypt(validated_data['password'])
        return super(DatabaseConfigSerializer, self).create(validated_data)

    def update(self, instance, validated_data):
        raw_password = validated_data.get('password')
        if raw_password and raw_password != instance.password:
            pcrypt = PasswordCrypt()
            validated_data['password'] = pcrypt.encrypt(raw_password)
        return super(DatabaseConfigSerializer, self).update(instance, validated_data)

    class Meta:
        model = DatabaseConfig
        fields = '__all__'


class AuditSQLSerializer(serializers.ModelSerializer):
    utime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    ctime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)

    def to_representation(self, instance):
        result = super(AuditSQLSerializer, self).to_representation(instance)
        result['group'] = instance.group.name
        result['commiter'] = instance.commiter.name
        result['treater'] = instance.treater.name
        result['database'] = instance.database.name
        result['status'] = instance.status
        return result

    class Meta:
        model = AuditSQL
        fields = '__all__'
